package com.ecloud.scheduler.job;

import com.alibaba.fastjson.JSON;
import com.ecloud.client.HbaseClient;
import com.ecloud.client.TrendClient;
import com.ecloud.common.JsonResult;
import com.ecloud.common.exception.JsonResultException;
import com.ecloud.common.util.TimeUtil;
import com.ecloud.trend.entities.TdbDaily;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;

/**
 * 每日数据任务
 *
 * @author Squbi
 * @date 2021/7/19 10:11
 */
@Component
public class DailyDataTransferJob implements SimpleJob {
    private static final Logger logger = LoggerFactory.getLogger(DailyDataTransferJob.class);

    @Autowired
    private HbaseClient hbaseClient;

    @Autowired
    private TrendClient trendClient;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        //获取触发器的名称及其组名称，获取作业详细信息的名称及其组名称.
        String triggerName = context.getTrigger().getKey().getName();
        String jobDetailName = context.getJobDetail().getKey().getName();
        logger.info("开始执行 {},触发器 {}", jobDetailName, triggerName);
        job();
    }

    public void job() {
        JsonResult jsonResult = trendClient.tdbYesterday();
        if (!jsonResult.isSuccess()) {
            throw new JsonResultException(jsonResult);
        }
        List<TdbDaily> tdbDailies = jsonResult.unpackArray(TdbDaily.class);
        HashMap<String, String> map = new HashMap<>();
        for (TdbDaily tdbDaily : tdbDailies) {
            String tagNumber = tdbDaily.getTagNumber();
            String json = JSON.toJSONString(tdbDaily);
            map.put(tagNumber, json);
        }
        JsonResult result = hbaseClient.postDaily(map, TimeUtil.yesterday());
        logger.info("执行结果 :> {}", result);
    }
}
